import { omit } from 'lodash-es'
import { MULTI_TAB_STORE_KEY } from '@/layouts/multi-tab/type.ts'
import { useGlobalConfig } from '@/composables/global-config.ts'

/**
 * @ProjectName： naive-admin
 * @FileName： multi-tab-state
 * @Description: // 多页签状态管理
 * @Author: ellwood
 * @date: 2024/2/5 - 8:12
 * @Version: V1.0.0
 */
export function useMultiTabProvider() {
  let g = 0
  const guid = () => `CacheTab_${++g}`

  const state = reactive({
    // tab列表
    tabList: [],
    // 选中的数据
    current: '',
    guid,
    componentCache: {},
  })

  provide(MULTI_TAB_STORE_KEY, state)

  // 返回选中的状态信息
  return state
}

export function useMultiTabInject() {
  // 给他加一个！我们确定是一定有值的
  return inject(MULTI_TAB_STORE_KEY)!
}

export function useMultiTab() {
  // 获取数据状态
  const state = useMultiTabInject()
  const route = useRoute()
  const router = useRouter()
  const tabList = computed(() => state.tabList)
  const current = computed(() => state.current)
  const { message } = useGlobalConfig()
  const componentCache = toRaw(state.componentCache)

  const closeTab = (path?: string) => {
    if (!path)
      path = current.value

    if (tabList.value.length <= 1)
      message?.info('这是最后一个标签页，无法被关闭')

    const currentIndex = tabList.value.findIndex(item => item.path === path)
    const currentItem = tabList.value[currentIndex]
    if (path !== current.value) {
      state.tabList.splice(currentIndex, 1)
      if (componentCache[currentItem.key!])
        delete componentCache[currentItem.key!]
      return
    }

    // 如果关闭的是当前页签
    // 如果当前页签不是第一个页签的话，我们让路由跳转到我们的上一个页签
    // 如果当前页签是第一个页签的话，我们让路由跳转到我们的下一个页签
    const targetIndex = currentIndex === 0 ? currentIndex + 1 : currentIndex - 1
    router.replace(tabList.value[targetIndex].route!).then(() => {
      state.tabList.splice(currentIndex, 1)
      if (componentCache[currentItem.key!])
        delete componentCache[currentItem.key!]
    })
  }

  const refresh = (path?: string) => {
    if (!path)
      path = current.value

    const currentIndex = tabList.value.findIndex(item => item.path === path)
    const currentItem = tabList.value[currentIndex]
    state.tabList[currentIndex] = { ...toRaw(currentItem), key: state.guid() }

    if (componentCache[currentItem.key!])
      delete componentCache[currentItem.key!]

    router
      .replace(currentItem.route!)
      .then(() => {
      })
      .catch(() => {
      })
  }

  watch(
    () => route.fullPath,
    () => {
      if (current.value !== route.path)
        state.current = route.path

      const tabIndex = state.tabList.findIndex(
        item => item.path === route.path,
      )
      if (tabIndex !== -1) {
        // 更新一下路由信息
        state.tabList[tabIndex].route = omit(route, ['matched'])
      }
      else {
        // 添加路由信息
        /* const item: TabItem = {
                  route: omit(route, 'matched'),
                  path: route.path,
                  tabTitle: route.meta.title
                }
                state.tabList.push(item) */
      }
    },
    {
      immediate: true,
    },
  )

  return { tabList, current, closeTab, refresh }
}
